﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using OpenTKLightingTool.Helper;

namespace OpenTKLightingTool.Controls
{
    /// <summary>
    /// TextBox for entering the float value
    /// </summary>
    internal class FloatTextBox: TextBox
    {
        /// <summary>
        /// Min and Max values
        /// </summary>
        public static DependencyProperty MinValueProperty;
        public static DependencyProperty MaxValueProperty;

        static FloatTextBox()
        {
            MinValueProperty = DependencyProperty.Register("MinValue", typeof(float), typeof(FloatTextBox),
                                new PropertyMetadata(0f));
            MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(float), typeof(FloatTextBox),
                                new PropertyMetadata(1f));
        }

        public FloatTextBox()
        {
            Height = 20;
            this.LostFocus += FloatTextBox_LostFocus;
        }


        public float MinValue
        {
            get { return (float)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }

        public float MaxValue
        {
            get { return (float)GetValue(MaxValueProperty); }
            set { SetValue(MaxValueProperty, value); }
        }

        public float Value
        {
            get
            {
                float value;
                Parse.ParseFloat(Text, out value);
                return value;
            }
            set
            {
                Text = Convert.ToString(value);
            }
        }


        /// <summary>
        /// Called when text has changed
        /// </summary>
        private void FloatTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            float value;
            if (Parse.ParseFloat(Text, out value) == false)
            {
                value = MinValue;
            }

            if (value < MinValue)
                value = MinValue;
            if (value > MaxValue)
                value = MaxValue;

            Text = Convert.ToString(value);
        }
    }
}
